import * as React from 'react';
import { connect } from 'react-redux';
import Login from './Login';
import App from '../app/App';
import LoadingComponent from '../common/LoadingComponent';
import { loginWithToken, readyToLogin, localStorageKey } from './myAuthAction';
import { AuthStatus } from './AuthStatus';

interface IProps {
  isAuthenticated: boolean;
  authStatus: AuthStatus;
  dispatch: any;
}

class Authentication extends React.Component<IProps, any> {
  componentDidMount() {
    const { dispatch } = this.props;
    const token = localStorageKey.getToken();
    const loginSessionId = localStorageKey.getLoginSessionId();
    if (token && loginSessionId) {
      // use the token to login automatically for the user
      dispatch(loginWithToken(token, loginSessionId));
    } else {
      dispatch(readyToLogin());
    }
  }

  render() {
    const { isAuthenticated, authStatus } = this.props
    return (
      <div>
        {authStatus !== AuthStatus.NotReady ? (
          authStatus === AuthStatus.LoginWithToken ? (
            <LoadingComponent message='自动登录中...' />
          ) : (
              isAuthenticated ? <App /> : <Login />
            )
        ) : null}
      </div>
    );
  }
}

const mapStateToProps = (state: any) => ({
  isAuthenticated: state.authReducer.isAuthenticated,
  authStatus: state.authReducer.authStatus,
});

export default connect(mapStateToProps)(Authentication);
